﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Data;
using System.Reflection;

/// <summary>
/// ConvertClass 数据格式转换类
/// </summary>
public class ConvertClass
{
    /// <summary>
    /// 把datatable转化为Json字符串
    /// </summary>
    /// <param name="soureTable">要转换的DataTable</param>
    /// <returns>Json字符串</returns>
    public static string ConvertDataTableToJson(System.Data.DataTable soureTable)
    {
        string result = "";
        result = JsonConvert.SerializeObject(soureTable, new DataTableConverter());
        return result;
    }
    /// <summary>
    /// 实体类转化为Json
    /// </summary>
    /// <typeparam name="T">要转换的实体类的类型</typeparam>
    /// <param name="obj">要转化的实体类对象</param>
    /// <returns></returns>
    public static string ConvertClassToJson<T>(object obj)
    {
        string result = String.Empty;
        try
        {
            System.Runtime.Serialization.Json.DataContractJsonSerializer serializer =
            new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                serializer.WriteObject(ms, obj);
                result = System.Text.Encoding.UTF8.GetString(ms.ToArray());
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return result;
    }
    /// <summary>
    /// 转换List<T>的数据为JSON格式
    /// </summary>
    /// <typeparam name="T">类</typeparam>
    /// <param name="vals">列表值</param>
    /// <returns>JSON格式数据</returns>
    public static string JSON<T>(List<T> vals)
    {
        System.Text.StringBuilder st = new System.Text.StringBuilder();
        try
        {
            System.Runtime.Serialization.Json.DataContractJsonSerializer s = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));

            foreach (T city in vals)
            {
                using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                {
                    s.WriteObject(ms, city);
                    st.Append(System.Text.Encoding.UTF8.GetString(ms.ToArray()));
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }

        return st.ToString();
    }
    /// <summary>
    /// JSON格式字符转换为T类型的对象
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="jsonStr"></param>
    /// <returns></returns>
    public static T ParseFormByJson<T>(string jsonStr)
    {
        T obj = Activator.CreateInstance<T>();
        using (System.IO.MemoryStream ms =
        new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(jsonStr)))
        {
            System.Runtime.Serialization.Json.DataContractJsonSerializer serializer =
            new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));
            return (T)serializer.ReadObject(ms);
        }
    }
    /// <summary>
    /// 将dataTable转化List
    /// </summary>
    /// <typeparam name="T">要转化的类型</typeparam>
    /// <param name="table">要转化的DataTable</param>
    /// <returns></returns>
    public static IList<T> ConvertTo<T>(DataTable table)
    {
        if (table == null)
            return null;
        List<DataRow> rows = new List<DataRow>();
        foreach (DataRow row in table.Rows)
            rows.Add(row);
        return ConvertTo<T>(rows);
    }
    /// <summary>
    /// 将dataTable的Row转化List
    /// </summary>
    /// <typeparam name="T">要转化的类型</typeparam>
    /// <param name="rows">要转化的行</param>
    /// <returns></returns>
    public static IList<T> ConvertTo<T>(IList<DataRow> rows)
    {
        IList<T> list = null;
        if (rows != null)
        {
            list = new List<T>();
            foreach (DataRow row in rows)
            {
                T item = CreateItem<T>(row);
                list.Add(item);
            }
        }
        return list;
    }

    public static T CreateItem<T>(DataRow row)
    {
        string columnName;
        T obj = default(T);
        if (row != null)
        {
            obj = Activator.CreateInstance<T>();
            foreach (DataColumn column in row.Table.Columns)
            {
                columnName = column.ColumnName;
                //Get property with same columnName
                PropertyInfo prop = obj.GetType().GetProperty(columnName);
                try
                {
                    //Get value for the column
                    object value = (row[columnName].GetType() == typeof(DBNull))
                    ? null : row[columnName];
                    //Set property value
                    if (prop.CanWrite)    //判断其是否可写
                        prop.SetValue(obj, value, null);
                }
                catch
                {
                    throw;
                    //Catch whatever here
                }
            }
        }
        return obj;
    }
}